import React, { useEffect, useState } from 'react';
import { View, Text, Button, ActivityIndicator, StyleSheet } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage'; // 用于React Native的持久化存储
import { registerUser, loginUser, logoutUser, refreshToken, getUserProfile } from '../../api/auth'; // 假设路径正确

const AuthTest = () => {
    // 状态管理
    const [accessTokenExists, setAccessTokenExists] = useState<boolean>(false);
    const [refreshTokenExists, setRefreshTokenExists] = useState<boolean>(false);
    const [loading, setLoading] = useState<boolean>(false);
    const [message, setMessage] = useState<string>('');

    // 加载令牌状态
    useEffect(() => {
        const loadTokensStatus = async () => {
            try {
                const access = await AsyncStorage.getItem('access_token');
                const refresh = await AsyncStorage.getItem('refresh_token');
                setAccessTokenExists(!!access);
                setRefreshTokenExists(!!refresh);
                if (access || refresh) {
                    setMessage('Tokens loaded from storage.');
                }
            } catch (e) {
                console.error('Failed to load tokens from storage', e);
                setMessage('Error loading tokens.');
            }
        };
        loadTokensStatus();
    }, []);

    // 保存令牌到 AsyncStorage
    const saveTokens = async (access: string, refresh: string) => {
        try {
            await AsyncStorage.setItem('access_token', access);
            await AsyncStorage.setItem('refresh_token', refresh);
            setAccessTokenExists(true);
            setRefreshTokenExists(true);
            setMessage('Tokens saved successfully!');
        } catch (e) {
            console.error('Failed to save tokens:', e);
            setMessage('Error saving tokens.');
        }
    };

    // 移除令牌从 AsyncStorage
    const removeTokens = async () => {
        try {
            await AsyncStorage.removeItem('access_token');
            await AsyncStorage.removeItem('refresh_token');
            setAccessTokenExists(false);
            setRefreshTokenExists(false);
            setMessage('Tokens removed successfully!');
        } catch (e) {
            console.error('Failed to remove tokens:', e);
            setMessage('Error removing tokens.');
        }
    };

    const testRegister = async () => {
        setLoading(true);
        setMessage('Registering user...');
        try {
            // 使用一个带有时间戳的用户名，确保每次测试的用户名唯一
            const uniqueUsername = `testuser_${Date.now()}`;
            const response = await registerUser({
                username: uniqueUsername,
                password: 'password123', // 确保密码强度满足API要求
                nickname: 'Test User'
            });
            console.log('Register response:', response.data);
            // const { access, refresh } = response.data.data; // 根据API文档，access和refresh在data对象中 
            // await saveTokens(access, refresh); // 保存令牌
            setMessage(`User ${uniqueUsername} registered successfully!`);
        } catch (error: any) {
            console.error('Register error:', error.response?.data || error.message);
            setMessage(`Register failed: ${error.response?.data?.error?.message || error.message}`);
        } finally {
            setLoading(false);
        }
    };

    const testLogin = async () => {
        setLoading(true);
        setMessage('Logging in...');
        try {
            // 注意：这里使用的用户名和密码需要是您注册过的有效用户
            const response = await loginUser({
                username: 'alice', // 请替换为实际注册的用户名
                password: 'alice'
            });
            console.log('Login response:', response.data);
            const { access, refresh } = response.data.data; // 根据API文档，access和refresh在data对象中 
            await saveTokens(access, refresh); // 保存令牌
            setMessage('Login successful!');
        } catch (error: any) {
            console.error('Login error:', error.response?.data || error.message);
            setMessage(`Login failed: ${error.response?.data?.error?.message || error.message}`);
        } finally {
            setLoading(false);
        }
    };

    const testLogout = async () => {
        if (!refreshTokenExists) {
            setMessage('No refresh token available to logout.');
            return;
        }
        setLoading(true);
        setMessage('Logging out...');
        try {
            const currentRefreshToken = await AsyncStorage.getItem('refresh_token');
            if (!currentRefreshToken) {
                setMessage('Refresh token not found in storage for logout.');
                return;
            }
            const response = await logoutUser({ refresh: currentRefreshToken });
            console.log('Logout response:', response.data);
            await removeTokens(); // 移除令牌
            setMessage('Logout successful!');
        } catch (error: any) {
            console.error('Logout error:', error.response?.data || error.message);
            setMessage(`Logout failed: ${error.response?.data?.error?.message || error.message}`);
        } finally {
            setLoading(false);
        }
    };

    const testRefreshToken = async () => {
        if (!refreshTokenExists) {
            setMessage('No refresh token available to refresh.');
            return;
        }
        setLoading(true);
        setMessage('Refreshing token...');
        try {
            const currentRefreshToken = await AsyncStorage.getItem('refresh_token');
            if (!currentRefreshToken) {
                setMessage('Refresh token not found in storage for refresh.');
                return;
            }
            const response = await refreshToken({ refresh: currentRefreshToken });
            console.log('Refresh token response:', response.data);
            const { access, refresh } = response.data.data; // 根据API文档，access和refresh在data对象中 
            await saveTokens(access, refresh); // 保存新的令牌
            setMessage('Token refreshed successfully!');
        } catch (error: any) {
            console.error('Refresh token error:', error.response?.data || error.message);
            setMessage(`Refresh token failed: ${error.response?.data?.error?.message || error.message}`);
            // 如果刷新失败，很可能 refresh token 也失效了，需要清除所有令牌
            await removeTokens();
        } finally {
            setLoading(false);
        }
    };

    const testGetUserProfile = async () => {
        if (!accessTokenExists) {
            setMessage('No access token available. Please login first.');
            return;
        }
        setLoading(true);
        setMessage('Fetching user profile...');
        try {
            const response = await getUserProfile();
            console.log('Get user profile response:', response.data);
            setMessage('User profile fetched successfully!');
        } catch (error: any) {
            console.error('Get user profile error:', error.response?.data || error.message);
            setMessage(`Get user profile failed: ${error.response?.data?.error?.message || error.message}`);
            // 如果获取资料失败是由于 401，拦截器会尝试刷新。如果仍失败，表示令牌完全失效
            // 在这种情况下，拦截器已经处理了令牌清除，这里无需重复清除
        } finally {
            setLoading(false);
        }
    };

    return (
        <View style={styles.container}>
            <Text style={styles.header}>Auth API Test</Text>
            <Text style={styles.statusMessage}>{message}</Text>
            {loading && <ActivityIndicator size="small" color="#0000ff" style={styles.loadingIndicator} />}

            <View style={styles.buttonContainer}>
                <Button title="Register New User" onPress={testRegister} disabled={loading} />
            </View>
            <View style={styles.buttonContainer}>
                <Button title="Login User" onPress={testLogin} disabled={loading} />
            </View>
            <View style={styles.buttonContainer}>
                <Button title="Logout User" onPress={testLogout} disabled={loading || !refreshTokenExists} />
            </View>
            <View style={styles.buttonContainer}>
                <Button title="Refresh Access Token" onPress={testRefreshToken} disabled={loading || !refreshTokenExists} />
            </View>
            <View style={styles.buttonContainer}>
                <Button title="Get User Profile" onPress={testGetUserProfile} disabled={loading || !accessTokenExists} />
            </View>

            <Text style={styles.tokenStatus}>
                Access Token: {accessTokenExists ? 'Exists' : 'None'}
            </Text>
            <Text style={styles.tokenStatus}>
                Refresh Token: {refreshTokenExists ? 'Exists' : 'None'}
            </Text>
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        padding: 20,
    },
    header: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 20,
    },
    statusMessage: {
        fontSize: 16,
        color: 'gray',
        marginBottom: 10,
        textAlign: 'center',
    },
    loadingIndicator: {
        marginBottom: 10,
    },
    buttonContainer: {
        width: '80%',
        marginBottom: 10,
    },
    tokenStatus: {
        marginTop: 10,
        fontSize: 14,
        color: 'darkblue',
    },
});

export default AuthTest;